package com.koron.css2.clientCenter.impl;

import cn.hutool.core.date.DateTime;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.clientCenter.bean.UserChangeItemBean;
import com.koron.css2.clientCenter.bean.UserGroupBean;
import com.koron.css2.clientCenter.mapper.ChangeUserImportMapper;
import com.koron.css2.clientCenter.mapper.ChangeUserMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserGroupMapper;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.mapper.TWaterCompanyMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.workflow.ProcessInterface;
import com.koron.util.Constant;
import com.koron.util.secret.RequestBean;
import com.koron.util.secret.SecretReqUtil;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ChangeUserImportProcess implements ProcessInterface{

	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, int operation) {
		MessageBean<?> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
		try {
			if("approval".equalsIgnoreCase(fromNodeCode) && 32 == operation) {
				ChangeUserMapper changeMapper = factory.getMapper(ChangeUserMapper.class);
				ChangeUserImportMapper mapper = factory.getMapper(ChangeUserImportMapper.class);
				UserGroupMapper groupMapper = factory.getMapper(UserGroupMapper.class);
				PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class,"_default");
				ChangeUserMapper changeUserMapper = factory.getMapper(ChangeUserMapper.class);
				CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
				//获取登录水司库名
				TWaterCompanyMapper tWaterCompanyMapper = factory.getMapper(TWaterCompanyMapper.class,"_default");
				String dataBaseName= tWaterCompanyMapper.selectDataBaseByCode(userInfo.getCurWaterCode());
				//更新当前账期的相关账单的冗余字段
				String accountPeriod=CommonUtils.getYearMonth();
				mapper.workflowEndUpdateAccountInfo(billId);
				mapper.workflowEndUpdateCtmInfo(billId);
				mapper.workflowEndUpdateUserInfo(billId);
				mapper.updateBillDetailCtmName(billId, accountPeriod);
				/**
				 * 根据变更内容将变更字段置空
				 */
				//获取变更内容
				List<String> listUserNo  =  changeUserMapper.selectUserNoGroupByBillId(billId);
				List<String> ctmInfoColumns = changeUserMapper.selectTableColumns("user_ctm",dataBaseName);
				List<String> accountInfoColumns = changeUserMapper.selectTableColumns("user_account",dataBaseName);
				List<String> userInfoColumns = changeUserMapper.selectTableColumns("user_info",dataBaseName);
				for (String userNo : listUserNo) {
					List<UserChangeItemBean> items = changeUserMapper.selectChangeItemfromTemp(billId,userNo);
					List<UserChangeItemBean> items1 = new ArrayList<>();//用户变更内容
					List<UserChangeItemBean> items3 = new ArrayList<>();//客户变更内容
					List<UserChangeItemBean> items2 = new ArrayList<>();//账户变更内容
					//获取用户、客户、账户表字段
					for (UserChangeItemBean userChangeItemBean : items) {
						if (userInfoColumns.contains(userChangeItemBean.getChangeCode())) {
							items1.add(userChangeItemBean);
						}
						if (ctmInfoColumns.contains(userChangeItemBean.getChangeCode())) {
							items3.add(userChangeItemBean);
						}
						if (accountInfoColumns.contains(userChangeItemBean.getChangeCode())) {
							items2.add(userChangeItemBean);
						}
					}
					//修改客户表变更内容
					//拼接动态修改sql
					if (items3.size() != 0) {
						StringBuilder updateSql = new StringBuilder("update user_ctm set ");
						for (int i = 0; i < items3.size(); i++) {
							String value = items3.get(i).getNewItemValue();
							if (i == 0) {
								updateSql.append(items3.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							} else {
								updateSql.append("," + items3.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							}
						}
						updateSql.append("," + "update_account =" + "'" + items3.get(0).getCreateAccount() + "'");
						updateSql.append("," + "update_name =" + "'" + items3.get(0).getCreateName() + "'");
						updateSql.append("," + "update_time =" + "'" + new DateTime() + "'");
						updateSql.append("where ctm_no =" + "'" + items3.get(0).getCtmNo() + "'");
						System.out.println(updateSql);
						ctmMapper.ctmInfoUpdateNull(updateSql.toString());
					}
					//修改账户表变更内容
					//拼接动态修改sql
					if (items2.size() != 0) {
						StringBuilder updateSql = new StringBuilder("update user_account set ");
						for (int i = 0; i < items2.size(); i++) {
							String value = items2.get(i).getNewItemValue();
							if (i == 0) {
								updateSql.append(items2.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							} else {
								updateSql.append("," + items2.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							}
						}
						updateSql.append("," + "update_account =" + "'" + items2.get(0).getCreateAccount() + "'");
						updateSql.append("," + "update_name =" + "'" + items2.get(0).getCreateName() + "'");
						updateSql.append("," + "update_time =" + "'" + new DateTime() + "'");
						updateSql.append("where account_no =" + "'" + items2.get(0).getAccountNo() + "'");
						System.out.println(updateSql);
						ctmMapper.ctmInfoUpdateNull(updateSql.toString());
					}
					//修改用户表变更内容
					//拼接动态修改sql,重新更新变更字段（包括置空的字段）
					if (items1.size() != 0) {
						StringBuilder updateSql = new StringBuilder("update user_info set ");
						for (int i = 0; i < items1.size(); i++) {
							String value = items1.get(i).getNewItemValue();
							if (i == 0) {
								updateSql.append(items1.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							} else {
								updateSql.append("," + items1.get(i).getChangeCode() + "=" + (value.equals("空") ? null : "'" + value + "'"));
							}
						}
						updateSql.append("," + "update_account =" + "'" + items1.get(0).getCreateAccount() + "'");
						updateSql.append("," + "update_name =" + "'" + items1.get(0).getCreateName() + "'");
						updateSql.append("," + "update_time =" + "'" + new DateTime() + "'");
						updateSql.append("where user_no =" + "'" + items1.get(0).getUserNo() + "'");
						System.out.println(updateSql);
						ctmMapper.ctmInfoUpdateNull(updateSql.toString());
					}
				}

				/**
				 * 不存在的用户组编号则按规则生成
				 */
				List<UserGroupBean> list = mapper.selectGroupNo(billId);
				
				for (UserGroupBean bean : list) {
					if(StringUtils.isBlank(bean.getUserGroupNo())) {
						continue;
					}
					UserGroupBean isExit = groupMapper.selectByNo(bean.getUserGroupNo());
					//为空代表组编号不存在需要生成
					if(isExit==null) {
						UserGroupBean newBean = new UserGroupBean();
						newBean.setCreateInfo(userInfo);
						newBean.setUserGroupNo(bean.getUserGroupNo());
						String clientAddrId = pmapper.getNameById(bean.getUserGroupName());
						//获取结构化地址中文名
						newBean.setUserGroupName(clientAddrId==null?"":clientAddrId);
						//newBean.setBookNo(bean.getBookNo());
						newBean.setSortNo(bean.getUserGroupNo());
						groupMapper.add(newBean);
					}
				}
				//更新变更事项到正式表
				changeMapper.userChangeItemfromTemp(billId);
				//更新变更信息到集抄
				List<Map<String,Object>> jcList=changeMapper.getUserChangeInfo(billId);
				if(jcList!=null) {//不为空，则传至集抄系统
					 logger.info("用户信息变更同步至集抄系统"+update(ApplicationConfig.getJcUrl(),jcList));
				}
			}
		} catch (Exception e) {
			factory.close(false);
			logger.error("批量变更审批后续操作失败", e);
			info = MessageBean.create(Constant.MESSAGE_INT_FAIL, "批量变更审批后续操作失败", Void.class);
		}
		return info;
	}
	 private static String update(String url, List<Map<String,Object>> list){
		
	    	RequestBean reqBean = new RequestBean();
	        reqBean.setUrl(url);
	        reqBean.setData(list);
	        String result = null;
	        try {
	            result = SecretReqUtil.sendToJc(reqBean,"updateUserInfo");
	            
	        }catch (Exception e){
	            logger.error("调用集抄系统失败",e);
	            return e+"";
	        }
	        return result;
	    }
	@Override
	public MessageBean<?> before(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, int operation) {
		return exec(factory, userInfo, billId, fromNodeCode, operation);
	}

	@Override
	public MessageBean<?> after(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, String toNodeCode) {
		return null;
	}
}
